/**
 * @file: RoughInsert.java
 *
 * @author: 蒋振
 *
 * @date: 2016年4月11日 下午2:08:14
 *
 * @copyright: 南京凯盛
 */
package cn.com.kisen.db.mongo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;


/**
 * 
 *
 * @author 蒋振
 * @version 1.0 Created on 2016年4月11日 下午2:08:14
 */
public class RoughInsert {
    
    private RoughInsert(){}
    
    private static RoughInsert instance = new RoughInsert();
    
    private static Logger logger = Logger.getLogger(RoughInsert.class);
    
    /**
     * 插入1秒内的采样数据
     * 
     * @param collection
     * @param sec
     * @author: 蒋振
     * @date: Created on 2016年4月11日 下午2:56:15
     */
    private void batchInsertOneSec(MongoCollection<Document> collection, int sec){
        
        // 文档集合
        List<Document> documents = new ArrayList<Document>();
        // 准备文档集合 模拟  boolean
        for(int tagID=Tag.boolPtsBgn;tagID<=Tag.boolPtsEnd;tagID++){
            Document document = new Document("tag",tagID).
                    append("sec",sec).
                    // n________n________n________  
                    append("value",sec%100==0);
            documents.add(document);
        }
        // 准备文档集合 模拟 integer
        for(int tagID=Tag.integerPtsBgn;tagID<=Tag.integerPtsEnd;tagID++){
            Document document = new Document("tag",tagID).
                    append("sec",sec).
                    // 随着时间递增 +1/100s
                    append("value",sec/100);
            documents.add(document);
        }
        // 准备文档集合 模拟 double
        for(int tagID=Tag.doublePtsBgn;tagID<Tag.doublePtsEnd;tagID++){
            Document document = new Document("tag",tagID).
                    append("sec",sec).
                    // 随着时间递增 +1/100s
                    append("value",sec/100+0.1D);
            documents.add(document);
        }
        
        // 插入文档集合
        collection.insertMany(documents);
        logger.info(String.format("%2d:%2d:%2d", 
                sec/(60*60),    // 取小时
                (sec/60)%60,    // 取分钟
                sec%60));       // 取秒数
    }
    
    private void compressBooleanTag(
            MongoCursor<Document> mongoCursor,
            MongoCollection<Document> targetC) throws Exception{
        // 比较值
        Document pre = null;
        // 持续时间
        int duration = 0;
        while(mongoCursor.hasNext()){
            // 获得当前文档
            Document cur = mongoCursor.next();
            // 第一次处理
            if(pre==null){
                pre = cur;
                duration = 1;
            }else{
                // 若当前的文档与前一个文档的value值相等
                if(cur.getBoolean("value")==pre.getBoolean("value")){
                    duration++;
                    if(!mongoCursor.hasNext()){
                        pre.append("duration", duration);
                        targetC.insertOne(getNewDoc(pre,duration));
                        pre = cur;
                        duration = 1;
                    }
                }else{  // 不等
                    pre.append("duration", duration);
                    targetC.insertOne(getNewDoc(pre,duration));
                    pre = cur;
                    duration = 1;
                }
            }
        }  
    }
    
    private void compressIntegerTag(
            MongoCursor<Document> mongoCursor,
            MongoCollection<Document> targetC) throws Exception{
        // 比较值
        Document pre = null;
        // 持续时间
        int duration = 0;
        while(mongoCursor.hasNext()){
            // 获得当前文档
            Document cur = mongoCursor.next();
            // 第一次处理
            if(pre==null){
                pre = cur;
                duration = 1;
            }else{
                // 若当前的文档与前一个文档的value值相等
                if(cur.getInteger("value").intValue()==pre.getInteger("value").intValue()){
                    duration++;
                    if(!mongoCursor.hasNext()){
                        pre.append("duration", duration);
                        targetC.insertOne(getNewDoc(pre,duration));
                        pre = cur;
                        duration = 1;
                    }
                }else{  // 不等
                    pre.append("duration", duration);
                    targetC.insertOne(getNewDoc(pre,duration));
                    pre = cur;
                    duration = 1;
                }
            }
        }  
    }
    
    private void compressDoubleTag(
            MongoCursor<Document> mongoCursor,
            MongoCollection<Document> targetC) throws Exception{
        // 比较值
        Document pre = null;
        // 持续时间
        int duration = 0;
        while(mongoCursor.hasNext()){
            // 获得当前文档
            Document cur = mongoCursor.next();
            // 第一次处理
            if(pre==null){
                pre = cur;
                duration = 1;
            }else{
                // 若当前的文档与前一个文档的value值相等
                if(cur.getDouble("value").doubleValue()==pre.getDouble("value").doubleValue()){
                    duration++;
                    if(!mongoCursor.hasNext()){
                        pre.append("duration", duration);
                        targetC.insertOne(getNewDoc(pre,duration));
                        pre = cur;
                        duration = 1;
                    }
                }else{  // 不等
                    pre.append("duration", duration);
                    targetC.insertOne(getNewDoc(pre,duration));
                    pre = cur;
                    duration = 1;
                }
            }
        }  
    }
    
    private Document getNewDoc(Document oldDoc,int duration) throws Exception{
        Document newDoc = new Document();
        newDoc.append("tag", oldDoc.getInteger("tag"));
        newDoc.append("sec", oldDoc.getInteger("sec"));
        
        // Tag 类型
        TagType type = Tag.getTagType(oldDoc.getInteger("tag"));
        if(type==TagType.BOOLEAN){
            newDoc.append("value", oldDoc.getBoolean("value"));
        }else if(type==TagType.INTEGER){
            newDoc.append("value", oldDoc.getInteger("value"));
        }else if(type==TagType.DOUBLE){
            newDoc.append("value", oldDoc.getDouble("value"));
        }else{
            throw new Exception("tag type unknown");
        }
        newDoc.append("duration", duration);
        return newDoc;
    }
    
    public static RoughInsert getInstance(){
        return instance;
    }
    
    public void batchInsertOneDay(){
        
        // 获得MongoDB客户端
        MongoClient     mongoClient = new MongoClient("localhost",27017);
        // 获得数据库 - "sample"
        MongoDatabase   mongoDatabase = mongoClient.getDatabase("sample");
        // 准备集合名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String collectionName = sdf.format(new Date());
        // 创建当天的集合
        mongoDatabase.createCollection(collectionName);
        // 获得当天的集合
        MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName);
        collection.createIndex(new BasicDBObject("tag", 1));
        collection.createIndex(new BasicDBObject("sec", 1));
        logger.info(collectionName + " sampling is running ");
        for(int i=0;i<24*60*60;i++){
            batchInsertOneSec(collection,i);
        }
        logger.info(collectionName + " sampling is over ");
        // 关闭MongoDB客户端
        mongoClient.close();
    }
    
    public void compress(String collectionName) throws Exception{
        // 获得MongoDB客户端
        MongoClient     mongoClient = new MongoClient("localhost",27017);
        // 获得数据库 - "sample"
        MongoDatabase   mongoDatabase = mongoClient.getDatabase("sample");
        // 获得当天的集合
        MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName);
        // 创建压缩集合
        mongoDatabase.createCollection(collectionName+"-compress");
        MongoCollection<Document> collectionC = mongoDatabase.getCollection(collectionName+"-compress");
        collectionC.createIndex(new BasicDBObject("tag", 1));
        collectionC.createIndex(new BasicDBObject("sec", 1));
        
        // 压缩算法 Boolean
        for(int tag=Tag.boolPtsBgn;tag<=Tag.boolPtsEnd;tag++){
            // 查询某个tag一天内的所有的数据
            MongoCursor<Document> mongoCursor = collection.find(Filters.eq("tag", tag)).iterator(); 
            compressBooleanTag(mongoCursor,collectionC);
            mongoCursor.close();
            System.out.print(String.format("tag : %6d compressed%n",tag));
        }
        // Integer
        for(int tag=Tag.integerPtsBgn;tag<=Tag.integerPtsEnd;tag++){
            // 查询某个tag一天内的所有的数据
            MongoCursor<Document> mongoCursor = collection.find(Filters.eq("tag", tag)).iterator(); 
            compressIntegerTag(mongoCursor,collectionC);
            mongoCursor.close();
            System.out.print(String.format("tag : %6d compressed%n",tag));
        }
        // Double
        for(int tag=Tag.doublePtsBgn;tag<Tag.doublePtsEnd;tag++){
            // 查询某个tag一天内的所有的数据
            MongoCursor<Document> mongoCursor = collection.find(Filters.eq("tag", tag)).iterator(); 
            compressDoubleTag(mongoCursor,collectionC);
            mongoCursor.close();
            System.out.print(String.format("tag : %6d compressed%n",tag));
        }
        
        // 关闭MongoDB客户端
        mongoClient.close();
    }

}
